﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using UIWindow.Domains;
using UIWindow.Models;

namespace UIWindow.GlobalParameters
{
    [Attributes.Singleton]
    public class ParameterGlobal
    {
        public RunParameterModel RunParameter { get; set; }
        public WeighingParameterModel WeighingParameter { get; set; }
        public DecideParameterModel DecideParameter { get; set; }
        public MESParameterModel MESParameter { get; set; }
        public object OPLCLock { get; set; } = new object();
        public ParameterGlobal()
        {
            if (!File.Exists(GlobalStart.ParameterPath))
            {
                WeighingParameter = new WeighingParameterModel();
                RunParameter = new RunParameterModel();
                DecideParameter = new DecideParameterModel();
                MESParameter = new MESParameterModel();
            }
            else
            {
                var model = JsonSerializer.Deserialize<Dictionary<string, object>>(File.ReadAllText(GlobalStart.ParameterPath, Encoding.UTF8));
                WeighingParameter = JsonSerializer.Deserialize<WeighingParameterModel>(model["WeighingParameter"].ToString());
                RunParameter = JsonSerializer.Deserialize<RunParameterModel>(model["RunParameter"].ToString());
                DecideParameter = JsonSerializer.Deserialize<DecideParameterModel>(model["DecideParameter"].ToString());
                MESParameter = JsonSerializer.Deserialize<MESParameterModel>(model["MESParameter"].ToString());
            }
        }

        public void Save() => File.WriteAllText(GlobalStart.ParameterPath, JsonSerializer.Serialize(this), Encoding.UTF8);
    }
}
